import axios from 'axios';

import { server_base_url } from '../config';
import { info } from './common';

export const auth = {
    /**
     * 登录接口
     * @param { string } account        注册账号
     * @param { string } password       注册密码
     */
    async login(account, password) {
        try {
            const response = await axios.post(`${ server_base_url }/user/login`, {
                account, password
            }, {
                headers: { 'Content-Type': 'application/json' }
            });
            const data = response.data;
            info('[ resposeData ] login', data);
            return { success: true, data };
        } catch (err) {
            info('[ err ] login', err);
            return { success: false, err };
        }
    },
    /**
     * 注册接口
     * @param { string } account        注册账号
     * @param { string } password       注册密码
     * @param { string } fundPassword   资金密码
     * @param { string } inviteCode     邀请码
     * @param { string } registerType   注册类型: { 0: 邮箱注册, 1: 手机注册 }
     * @param { string } code           验证码
     */
    async register(account, password, fundPassword, inviteCode, registerType=0, code='68794') {
        try {
            const response = await axios.post(`${ server_base_url }/user/register`, {
                account, password, fundPassword, inviteCode, registerType, code
            }, {
                headers: { 'Content-Type': 'application/json' }
            });
            const data = response.data;
            info('[ resposeData ] register', data);
            return { success: true, data };
        } catch (err) {
            info('[ err ] register', err);
            return { success: false, err };
        }
    },
    /**
     * 退出登录接口
     */
    async logout() {
        try {
            const token = localStorage.getItem('token');
            if (!token) throw new Error('token is null');
            const response = await axios.post(`${ server_base_url }/user/logout`, {}, {
                headers: { 'Content-Type': 'application/json', token }
            });
            const data = response.data;
            info('[ resposeData ] logout', data);
            return { success: true, data };
        } catch (err) {
            info('[ err ] logout', err);
            return { success: false, err };
        }
    },
};
